import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

// 把用户信息保存在 vuex 中
let USER
if (uni.getStorageSync('user') === "") {
  USER = {}
} else {
  USER = uni.getStorageSync('user')
}

let CART = []
if (uni.getStorageSync('cart') !== "") {
  CART = uni.getStorageSync('cart')
}

// 每隔 10 天，定时清理浏览器缓存 864000 秒为10天
if (uni.getStorageSync('startTime') == '') {
	uni.setStorageSync('startTime', Number(new Date()))
}
uni.setStorageSync('endTime', Number(new Date()))

let difTime = parseInt(uni.getStorageSync('endTime')) - parseInt(uni.getStorageSync('startTime'))
let dayTime = parseInt(difTime/(1000))
if (dayTime >= 864000 ) {
	uni.setStorageSync('startTime', Number(new Date()))
	uni.removeStorageSync('cart');
	CART = []
}

const store = new Vuex.Store({
	state: {
		user: USER,
		cart: CART
	},
	getters: {
		getUser(state) {
			return state.user
		},
		getCart(state) {
			return state.cart
		},
	},
	mutations: {
		// actions 提交过来的信息，保存用户信息
		ADDUSER(state, user) {
			state.user = user
			uni.setStorageSync('user', user);
		},
		
		// 添加购物车功能，
		ADDCART(state, cart) {
			if (cart.good.count >= 0) {
				cart.goods.forEach((good) => {
					good.foods.forEach((food) => {
						if (cart.good.id == food.id){
							if (food.stock > food.count) {
								cart.good.count++
								food.count = cart.good.count
								return
							}
							uni.showToast({
								icon: 'none',
								title: "没有库存了",
							})
						}
					})
				})
			
			} else {
				cart.goods.forEach((good) => {
					good.foods.forEach((food) => {
						if (cart.good.id == food.id) {
							if (food.stock <= 0) {
								uni.showToast({
									icon: 'none',
									title: "没有库存了",
								})
								return
							}
							Vue.set(food, 'count', 1)
						}
					})
				})
			}
			state.cart = cart.goods
			uni.setStorageSync('cart', cart.goods);
		},
		
		// 减少购物车数量
		DELCART(state, cart) {
			if (cart.good.count) {
				cart.good.count--
				cart.goods.forEach((good) => {
					good.foods.forEach((food) => {
						if (cart.good.id == food.id)
							food.count = cart.good.count
						// console.log('dec-shop', JSON.stringify(this.foods))
					})
				})
			}
			state.cart = cart.goods
			uni.setStorageSync('cart', cart.goods);
		},
		
		// 清空购物车
		DELALL(state, cart) {
			cart.goods.forEach((good) => {
				good.foods.forEach((food) => {
					if (food.count) {
						food.count = 0
						// console.log(JSON.stringify(food));
					}
				})
			})
			state.cart = []
			uni.removeStorageSync('cart');
		}
	},
	actions: {
		// 保存用户信息
		addUser({ commit }, user) {
			commit('ADDUSER', user)
		},
		
		// 往购物车中添加商品
		addCart({ commit }, cart) {
			commit('ADDCART', cart)
		},
		
		// 往购物车中删除商品
		delCart({ commit }, cart) {
			commit('DELCART', cart)
		},
		
		// 清空购物车
		delAll({ commit }, cart) {
			commit('DELALL', cart)
		},
	}
})

export default store
